package org.jeecg.modules.goods.rfqmanage.service.impl;

import org.jeecg.modules.goods.rfqmanage.entity.RfqManage;
import org.jeecg.modules.goods.rfqmanage.mapper.RfqManageMapper;
import org.jeecg.modules.goods.rfqmanage.service.IRfqManageService;
import org.jeecg.modules.goods.rfqmanage.dto.AuditRequestDto;
import org.jeecg.modules.goods.rfqmanagedetail.entity.RfqManageDetail;
import org.jeecg.modules.goods.rfqmanagedetail.service.IRfqManageDetailService;
import org.jeecg.modules.tplus.service.ITplusService;
import org.jeecg.modules.tplus.dto.InventoryInfoReqDto;
import org.jeecg.modules.tplus.dto.InventoryEntityReqDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.jeecg.common.util.oConvertUtils;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.math.BigDecimal;

/**
 * @Description: 询报价主信息
 * @Author: jeecg-boot
 * @Date:   2025-06-07
 * @Version: V1.0
 */
@Slf4j
@Service
public class RfqManageServiceImpl extends ServiceImpl<RfqManageMapper, RfqManage> implements IRfqManageService {

    @Autowired
    private IRfqManageDetailService rfqManageDetailService;

    @Autowired
    private ITplusService tplusService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdateWithDetail(RfqManage rfqManage, List<RfqManageDetail> rfqManageDetailList) {
        try {
            // 判断是新增还是修改
            boolean isUpdate = oConvertUtils.isNotEmpty(rfqManage.getId());

            if (isUpdate) {
                // 修改主信息
                this.updateById(rfqManage);

                // 删除原有明细信息
                LambdaQueryWrapper<RfqManageDetail> deleteWrapper = new LambdaQueryWrapper<>();
                deleteWrapper.eq(RfqManageDetail::getRfqId, rfqManage.getId());
                rfqManageDetailService.remove(deleteWrapper);
            } else {
                // 新增主信息
                this.save(rfqManage);
            }

            // 保存明细信息
            if (rfqManageDetailList != null && !rfqManageDetailList.isEmpty()) {
                for (RfqManageDetail detail : rfqManageDetailList) {
                    detail.setRfqId(rfqManage.getId());
                    detail.setId(null); // 确保明细信息重新生成ID
                }
                rfqManageDetailService.saveBatch(rfqManageDetailList);
            }

            return true;
        } catch (Exception e) {
            log.error("保存询报价信息失败", e);
            throw new RuntimeException("保存询报价信息失败: " + e.getMessage());
        }
    }

    @Override
    public IRfqManageService.RfqManageWithDetailVo queryWithDetailById(String id) {
        try {
            // 查询主信息
            RfqManage rfqManage = this.getById(id);
            if (rfqManage == null) {
                return null;
            }

            // 查询明细信息
            LambdaQueryWrapper<RfqManageDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RfqManageDetail::getRfqId, id);
            List<RfqManageDetail> rfqManageDetailList = rfqManageDetailService.list(queryWrapper);

            // 组装返回数据
            IRfqManageService.RfqManageWithDetailVo result = new IRfqManageService.RfqManageWithDetailVo();
            result.setRfqManage(rfqManage);
            result.setRfqManageDetailList(rfqManageDetailList);

            return result;
        } catch (Exception e) {
            log.error("查询询报价信息失败", e);
            throw new RuntimeException("查询询报价信息失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean auditRfq(AuditRequestDto auditRequest, String currentUser) {
        try {
            // 参数校验
            if (StringUtils.isEmpty(auditRequest.getId())) {
                throw new IllegalArgumentException("单据ID不能为空");
            }
            if (StringUtils.isEmpty(auditRequest.getAuditStatus())) {
                throw new IllegalArgumentException("审核状态不能为空");
            }
            // 审核不通过时，审核原因必填
            if ("0".equals(auditRequest.getAuditStatus()) && StringUtils.isEmpty(auditRequest.getAuditReason())) {
                throw new IllegalArgumentException("审核不通过时，审核原因不能为空");
            }

            // 查询单据是否存在
            RfqManage rfqManage = this.getById(auditRequest.getId());
            if (rfqManage == null) {
                throw new IllegalArgumentException("单据不存在");
            }

            // 更新审核信息
            rfqManage.setAuditStatus(auditRequest.getAuditStatus());
            rfqManage.setAuditReason(auditRequest.getAuditReason());
            rfqManage.setAuditTime(new Date());
            rfqManage.setUpdateBy(currentUser);
            rfqManage.setUpdateTime(new Date());

            // 保存审核结果
            boolean result = this.updateById(rfqManage);

            // 审核通过后，调用T+产品更新接口
            if (result && "1".equals(auditRequest.getAuditStatus())) {
                try {
                    updateTplusProductCost(auditRequest.getId());
                } catch (Exception e) {
                    log.error("调用T+产品更新接口失败，但审核已完成", e);
                    // 不影响审核流程，只记录日志
                }
            }

            return result;

        } catch (Exception e) {
            log.error("审核单据失败", e);
            throw new RuntimeException("审核失败：" + e.getMessage());
        }
    }

    /**
     * 更新T+产品成本
     * @param rfqId 询报价ID
     */
    private void updateTplusProductCost(String rfqId) {
        try {
            // 查询询报价明细
            LambdaQueryWrapper<RfqManageDetail> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RfqManageDetail::getRfqId, rfqId);
            List<RfqManageDetail> detailList = rfqManageDetailService.list(queryWrapper);

            if (detailList == null || detailList.isEmpty()) {
                log.warn("询报价ID: {} 没有找到明细数据，跳过T+产品成本更新", rfqId);
                return;
            }

            // 遍历明细，更新每个产品的成本
            for (RfqManageDetail detail : detailList) {
                if (StringUtils.isNotEmpty(detail.getGoodsCode())) {
                    updateSingleProductCost(detail);
                } else {
                    log.warn("询报价明细ID: {} 产品编码为空，跳过更新", detail.getId());
                }
            }

            log.info("T+产品成本更新完成，询报价ID: {}, 更新产品数量: {}", rfqId, detailList.size());

        } catch (Exception e) {
            // 记录异常但不影响审核流程
            log.error("更新T+产品成本失败，询报价ID: {}, 错误信息: {}", rfqId, e.getMessage(), e);
        }
    }

    /**
     * 更新单个产品成本
     * @param detail 询报价明细
     */
    private void updateSingleProductCost(RfqManageDetail detail) {
        if (detail.getGoodsCode() == null || detail.getGoodsCode().trim().isEmpty()) {
            log.warn("产品编码为空，跳过更新，明细ID: {}", detail.getId());
            return;
        }

        try {
            // 构建T+产品更新请求
            InventoryInfoReqDto request = buildInventoryUpdateRequest(detail);

            // 调用T+接口更新产品成本
            tplusService.inventoryUpdate(request);

            log.debug("T+产品成本更新成功，产品编码: {}, 大陆成本: {}, 香港成本: {}",
                detail.getGoodsCode(), detail.getMainlandQuotation(), detail.getHkQuotation());
        } catch (Exception e) {
            // 记录异常但继续处理其他产品
            log.error("更新单个产品成本失败，产品编码: {}, 错误信息: {}", detail.getGoodsCode(), e.getMessage(), e);
        }
    }

    /**
     * 构建T+产品更新请求
     * @param detail 询报价明细
     * @return T+产品更新请求
     */
    private InventoryInfoReqDto buildInventoryUpdateRequest(RfqManageDetail detail) {
        InventoryInfoReqDto request = new InventoryInfoReqDto();
        InventoryEntityReqDto inventoryEntity = new InventoryEntityReqDto();

        // 设置产品编码
        inventoryEntity.setCode(detail.getGoodsCode());

        // 构建动态属性，用于设置成本字段
        List<String> dynamicKeys = new ArrayList<>();
        List<Object> dynamicValues = new ArrayList<>();

        // 设置大陆成本和香港成本
        if (detail.getMainlandQuotation() != null) {
            // 设置大陆成本 (priuserdefdecm1)
            dynamicKeys.add("priuserdefdecm1");
            dynamicValues.add(detail.getMainlandQuotation());
        }

        if (detail.getHkQuotation() != null) {
            // 设置香港成本 (priuserdefdecm2)
            dynamicKeys.add("priuserdefdecm2");
            dynamicValues.add(detail.getHkQuotation());
        }

        // 设置动态属性
        if (!dynamicKeys.isEmpty()) {
            inventoryEntity.setDynamicPropertyKeys(dynamicKeys.toArray());
            inventoryEntity.setDynamicPropertyValues(dynamicValues.toArray());
        }

        request.setInventoryEntityReqDto(inventoryEntity);
        return request;
    }
}
